package Hot100;

import DMSXL._2023Before.ListNode_.ListNode;

public class reverseKGroup {
    public static void main(String[] args) {

        int[] listA = {1,2,3,4,5};
        int k = 3;
        ListNode headA = new ListNode(listA[0]);
        ListNode preA = headA;
        for (int i = 1; i < listA.length; i++) {
            ListNode temp = new ListNode(listA[i]);
            preA.next = temp;
            preA = preA.next;
        }
        ListNode rev = (reverseKGroup(headA,k));
        while (rev != null)
        {
            System.out.println(rev.val);
            rev = rev.next;
        }

    }
    public static ListNode reverseKGroup(ListNode head, int k) {
        int len = 0;
        ListNode prev = head;
        while(prev != null){
            len++;
            prev = prev.next;
        }
        ListNode first = new ListNode();
        if(len < k )
            return head;
        if(len == 0)
        {
            return null;
        }
        ListNode pre = new ListNode();
        pre.next = null;
        ListNode cur = head;
        int count = 0 ;
        int circle = len/k;
        int c_count = 0;
        boolean isfirst = false;
        while (cur != null){
            if(c_count == 0 && count < k)
                first = cur;
            if(count == k){
                c_count++;
                count = 0;
                for (int i = 0; i < k; i++) {
                    pre = pre.next;
                }
            }
            if(c_count < circle){
                ListNode next = cur.next;
                cur.next = pre.next;
                pre.next = cur;
                cur = next;
                count++;
            }
            else {
                pre.next = cur;
                break;
            }

        }

        return first;
    }
}
